<template>
  <div class="page-container">
    <el-container>
      <el-aside class="page-aside" width="280px" v-drag v-collapse>
        <div class="title">
          <div class="title-content">目录</div>
          <div class="title-button">
            <el-dropdown trigger="hover">
              <span class="title-button-box">
                <ac-icon iconId="018dc9c3efed46e8b927" size="18" @click.stop />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click.stop="addScriptGroovy({})">
                    <ac-icon iconId="018dc9c3efb74ac607cb" color="#67C23A" style="margin-right: 5px" /> 新增脚本
                  </el-dropdown-item>
                  <el-dropdown-item @click.stop="addFolder({})" :divided="true">
                    <ac-icon iconId="018dc9c3efed6d208a59" color="orange" style="margin-right: 5px" /> 新增目录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <div class="filter-box">
          <el-input placeholder="搜索" v-model="filterText" clearable />
        </div>
        <div class="page-aside-grow">
          <el-tree
            ref="tree"
            class="tree"
            node-key="id"
            v-loading="treeLoading"
            element-loading-text="数据加载中..."
            :data="treeData"
            :props="treeProps"
            :highlight-current="true"
            :default-expanded-keys="treeExpand"
            :filter-node-method="filterNode"
            @node-click="nodeClick"
          >
            <template v-slot="{ node, data }">
              <div class="node-item">
                <span class="icon">
                  <ac-icon v-if="node.expanded" color="orange" iconId="018dc9c3efedbb59d0b3" />
                  <ac-icon v-else color="orange" iconId="018dc9c3efed6d208a59" />
                </span>
                <span class="node-label" :title="data.text"><span>{{data.text}}</span></span>
                <div class="node-button">
                  <el-dropdown trigger="hover" placement="bottom-start">
                    <span class="node-button-item">
                      <ac-icon iconId="018dca6283a1e534a046" @click.stop />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="addScriptGroovy(data.data)">
                          <ac-icon iconId="018dc9c3efb74ac607cb" color="#67C23A" style="margin-right: 5px" />新增脚本
                        </el-dropdown-item>
                        <el-dropdown-item @click="addFolder(data.data)">
                          <ac-icon iconId="018dc9c3efed6d208a59" color="orange" style="margin-right: 5px" />新增目录
                        </el-dropdown-item>
                        <el-dropdown-item @click="updateNode(data.data)">
                          <ac-icon iconId="018dca6db20c6a3aaf68" color="#0085f6" style="margin-right: 5px" />修改目录
                        </el-dropdown-item>
                        <el-dropdown-item @click="moveNode(data.data)">
                          <ac-icon iconId="018dca444e0754edef13" color="#FF6600" style="margin-right: 5px" />移动目录
                        </el-dropdown-item>
                        <el-dropdown-item @click="deleteNode(data.data)">
                          <ac-icon iconId="018dc9c3efd3a0502886" color="#F56C6C" style="margin-right: 5px" />删除目录
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </template>
          </el-tree>
        </div>
      </el-aside>
      <el-main class="page-main">
        <ac-table
          ref="dataTable"
          pkName="id"
          :filters="filters"
          :filterFields="filterFields"
          :columns="columns"
          @handleTableOperator="handleTableOperator"
        ></ac-table>
      </el-main>
    </el-container>
  </div>

  <!--新增/编辑目录界面-->
  <el-dialog
    v-model="folderVisible"
    :title="folderTitle"
    width="500px"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <el-form
      ref="folderForm"
      label-width="120px"
      label-position="right"
      :model="folderData"
      :rules="folderRules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="目录名称" prop="name">
            <el-input v-model="folderData.name" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级目录" prop="parentId">
            <ac-tree
              v-model="folderData.parentId"
              dataUrl="/system/scriptFolder/queryTree"
              :leafSelect="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="folderVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="folderLoading"
        @click="submitFolderForm"
      >提交</el-button>
    </template>
  </el-dialog>

  <!--移动目录界面-->
  <el-dialog
    v-model="moveVisible"
    :title="moveTitle"
    width="500px"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <el-form
      ref="moveForm"
      label-width="120px"
      label-position="right"
      :model="moveData"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="目录">
            <ac-input
              v-model="moveData.name"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="移动到" prop="folderId">
            <ac-tree
              v-model="moveData.folderId"
              dataUrl="/system/scriptFolder/queryTree"
              :leafSelect="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="moveVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="moveLoading"
        @click="submitMoveForm"
      >提交</el-button>
    </template>
  </el-dialog>

  <!--脚本编辑-->
  <el-dialog
    v-model="dialogVisible"
    class="no-padding"
    :title="dialogTitle"
    :close-on-click-modal="false"
    destroy-on-close
    fullscreen
    draggable
  >
    <ScriptGroovyEdit ref="scriptGroovyRef" @afterSubmit="afterSubmit" :options="formData" />
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="dialogVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="dialogLoading"
        @click="submitDataForm"
      >提交</el-button>
    </template>
  </el-dialog>

  <!--脚本编辑-->
  <el-dialog
    v-model="historyVisible"
    class="no-padding"
    :title="historyTitle"
    :close-on-click-modal="false"
    destroy-on-close
    fullscreen
    draggable
  >
    <div class="history-box">
      <div class="header">
        <div class="history-left">
          <div class="title">
            <span>版本时间：</span>
            <el-select
              v-model="historyLeftId"
              @change="changeHistoryLeft"
              style="width: 200px"
            >
              <el-option
                v-for="history in historyList"
                :key="history.id"
                :label="history.updateTimeStr"
                :value="history.id"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="history-right">
          <div class="title">
            <span>版本时间：</span>
            <el-select
              v-model="historyRightId"
              @change="changeHistoryRight"
              style="width: 200px"
            >
              <el-option
                v-for="history in historyList"
                :key="history.id"
                :label="history.updateTimeStr"
                :value="history.id"
              ></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div ref="historyDiffView" class="body"></div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, nextTick, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import api from '@/http/api';
import ScriptGroovyEdit from "@/admin/codeless/scriptGroovyEdit.vue";

import CodeMirror from 'codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/addon/merge/merge.js';
import 'codemirror/addon/merge/merge.css';
import DiffMatchPatch from 'diff-match-patch';
import date from "@/utils/date";

const tree = ref();
const filterText = ref('');
const treeLoading = ref(false);
const treeKey = ref('');
const treeData = ref([]);
const treeExpand = ref([]);
const treeProps = ref({
  children: 'children',
  label: function(data) {
    return data.text +
      (data.data.code !== undefined && data.data.code != null
        ? ' [' + data.data.code + ']　' : '　')
  }
});
const currNode = ref(null);

const folderTitle = ref('');
const folderVisible = ref(false);
const folderLoading = ref(false);
const folderForm = ref();
const folderData = ref({});
const folderRules = ref({
  name: [{required: true, message: '请输入目录名称', trigger: ['blur', 'change']}],
});

const moveTitle = ref('');
const moveVisible = ref(false);
const moveLoading = ref(false);
const moveForm = ref();
const moveData = ref({});

const dataTable = ref();
const filters = ref({
  folderId: '',
  name: '',
});
const filterFields = ref([
  {prop: "name", label: "脚本编码/名称/内容"},
]);
const columns = ref([
  {prop: "name", label: "脚本名称", minWidth: 160},
  {prop: "id", label: "脚本编码", width: 180},
  {prop: "folderName", label: "目录名称", minWidth: 100},
  {prop: "updateTime", label: "更新时间", width: 160, align: 'center', type: "datetime"}
]);

const dialogVisible = ref(false);
const dialogTitle = ref('');
const dialogLoading = ref();
const scriptGroovyRef = ref();
const formData = ref({});

window.diff_match_patch = DiffMatchPatch
window.DIFF_DELETE = -1
window.DIFF_INSERT = 1
window.DIFF_EQUAL = 0

const historyDiffView = ref();
const historyMergeView = ref(null);
const historyVisible = ref(false);
const historyTitle = ref('');
const historyList = ref([]);
const historyLeftId = ref('');
const historyRightId = ref('');
const historyLeftScript = ref('');
const historyRightScript = ref('');

const filterNode = (value, data) => {
  if (!value) return true;
  return data.text.indexOf(value) >= 0
    || (data.data.code != null && data.data.code.indexOf(value) >= 0);
};

const nodeClick = (data, treeNode) => {
  if (currNode.value && currNode.value.id === data.id) {
    treeNode.checked = !treeNode.checked;
  } else {
    treeNode.checked = true;
  }

  if (treeNode.checked) {
    currNode.value = data;
    filters.value.folderId = data.id || '';
    dataTable.value.refreshPage(1);
  } else {
    tree.value.setCurrentKey(null);
    currNode.value = null;
    filters.value.folderId = '';
    dataTable.value.refreshPage(1);
  }
};

const addScriptGroovy = (data) => {
  formData.value = {folderId: data.id};
  dialogTitle.value = "新增脚本";
  dialogVisible.value = true;
};

const addFolder = (data) => {
  showFolderDialog('新增', {parentId: data.id || '', ordinal: 10});
};

const showFolderDialog = (tips, data) => {
  folderTitle.value = tips + '目录';
  folderVisible.value = true;
  folderData.value = Object.assign({}, data);
  folderForm.value && folderForm.value.resetFields();
};

const updateNode = (data) => {
  showFolderDialog('修改', data);
};

const moveNode = (data) => {
  moveTitle.value = '移动目录';
  moveVisible.value = true;
  moveData.value = {id: data.id, name: data.name, folderId: data.parentId};
  moveForm.value && moveForm.value.resetFields();
};

const deleteNode = (data) => {
  const url = '/system/scriptFolder/delete';
  ElMessageBox.confirm('请确认是否删除【' + data.name + '】？', '提示', {type: 'warning'}).then(() => {
    api.post(url, {id: data.id}).then(res => {
      ElMessage.success(res.message);
      treeExpand.value.push(data.parentId || '0');
      treeExpand.value.push(data.folderId || '0');
      treeKey.value = data.parentId || data.folderId || '0';
      loadTreeData();
    });
  }).catch(() => {});
};

const submitFolderForm = () => {
  folderForm.value && folderForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        folderLoading.value = true;
        api.post('/system/scriptFolder/save', folderData.value).then(res => {
          ElMessage.success(res.message);
          folderVisible.value = false;
          folderLoading.value = false;
          treeExpand.value.push(res.data.id || '0');
          treeKey.value = res.data.id || '0';
          loadTreeData();
        }).catch(() => {
          folderLoading.value = false;
        });
      }).catch(() => {});
    }
  });
};

const submitMoveForm = () => {
  moveForm.value && moveForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        moveLoading.value = true;
        const data = {id: moveData.value.id, parentId: moveData.value.folderId};
        const url = '/system/scriptFolder/updateParentId';
        api.post(url, data).then(res => {
          ElMessage.success(res.message);
          moveVisible.value = false;
          moveLoading.value = false;
          treeExpand.value.push(res.data.id || '0');
          treeKey.value = res.data.id || '0';
          loadTreeData();
        }).catch(() => {
          moveLoading.value = false;
        })
      }).catch(() => {});
    }
  });
};

const handleTableOperator = (button, row) => {
  if (button.buttonType === 'add') {
    formData.value = {folderId: filters.value.folderId};
    dialogTitle.value = "新增脚本";
    dialogVisible.value = true;
  } else if (button.buttonType === 'edit') {
    formData.value = {id: row.id};
    dialogTitle.value = "编辑脚本【" + row.name + "】";
    dialogVisible.value = true;
  } else if (button.buttonType === 'history') {
    historyTitle.value = "历史版本【" + row.name + "】";
    historyList.value = [];
    historyLeftId.value = '';
    historyRightId.value = '';
    historyLeftScript.value = '';
    historyRightScript.value = '';
    historyVisible.value = true;
    api.post('/system/scriptGroovyHistory/queryList', {groovyId: row.id}).then(res => {
      const resultList = [];
      (res.data || []).forEach(data => {
        data.updateTimeStr = date.formatLongDate(data.updateTime, 'yyyy-MM-dd HH:mm:ss');
        resultList.push(data);
      });
      historyList.value = resultList;
    });

    nextTick(() => {
      showDiff();
    });
  }
};

const changeHistoryLeft = () => {
  api.post('/system/scriptGroovyHistory/queryBy', {id: historyLeftId.value}).then(res => {
    historyLeftScript.value = res.data && res.data.script || '';
    showDiff();
  });
};

const changeHistoryRight = () => {
  api.post('/system/scriptGroovyHistory/queryBy', {id: historyRightId.value}).then(res => {
    historyRightScript.value = res.data && res.data.script || '';
    showDiff();
  });
};

const showDiff = () => {
  historyDiffView.value.innerHTML = '';

  historyMergeView.value = CodeMirror.MergeView(historyDiffView.value, {
    value: historyLeftScript.value,
    origLeft: null,
    orig: historyRightScript.value,
    lineNumbers: true,
    mode: "groovy",
    theme: 'dracula',
    highlightDifferences: true,
    showDifferences: true,
    revertButtons: true,
    connect: 'CodeMirror-merge-r-connect',
    height: '100%',
    gap: 1,
    readOnly: false,
  });
};

const submitDataForm = () => {
  scriptGroovyRef.value.submitData();
};

const afterSubmit = () => {
  dialogVisible.value = false;
  dataTable.value.findPage();
};

const loadTreeData = () => {
  treeLoading.value = true;
  api.post('/system/scriptFolder/queryTree').then(res => {
    const node = tree.value.getCurrentNode();
    if (node !== undefined && node != null) {
      treeExpand.value = [node.id, node.data.parentId, node.data.folderId, '0'];
    } else {
      treeExpand.value = ['0'];
    }
    treeData.value = res.data.children;
    treeLoading.value = false;
    if (treeKey.value) {
      nextTick(() => {
        tree.value.setCurrentKey(treeKey.value);
      });
    }
  }).catch(() => {
    treeLoading.value = false;
  });
};

watch(() => filterText.value, val => {
  tree.value.filter(val);
});

onMounted(() => {
  loadTreeData();
});
</script>

<style scoped lang="scss">
.title {
  display: flex;
  flex-direction: row;
  margin-right: 10px;
  height: 40px;
  align-items: center;

  .title-content {
    flex-grow: 1;
    font-size: 18px;
  }

  .title-button .title-button-box {
    height: 30px;
    width: 40px;
    border-radius: 5px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    border: none;
    cursor: pointer;
  }

  .title-button .title-button-box:hover {
    background: #eaeaea;
    border: none;
  }

  .title-button .title-button-box:focus-visible {
    outline: unset;
  }
}

.filter-box {
  margin-right: 10px;
}

.tree :deep(.el-tree-node__content) {
  height: 40px;
}

.page-aside-grow {
  width: 100% !important;

  :deep(.el-tree) {
    display: flex;
    flex-direction: column;
    width: 1px !important;
  }

  :deep(.el-tree-node) {
    display: flex;
    flex-direction: column;
    width: 100% !important;
  }

  :deep(.el-tree-node__content) {
    display: flex;
    flex-grow: 1;
  }
}

.node-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;

  .node-label {
    margin-left: 10px;
    flex-grow: 1;
    width: 1px;
    text-overflow: ellipsis;
    overflow: hidden;
    display: flex;

    > span {
      width: 100%;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
  .node-button {
    margin-right: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .node-button .node-button-item {
    height: 30px;
    width: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
  }
  .node-button .node-button-item:focus-visible {
    outline: unset;
  }
}
:deep(.el-tree-node:not(.is-current):focus>.el-tree-node__content) {
  background-color: unset!important;
}
:deep(.el-tree-node:focus>.el-tree-node__content) {
  background-color: unset!important;
}
:deep(.el-tree-node:focus>.el-tree-node__content:hover) {
  background-color: #f5f7fa!important;
}
:deep(.el-tree-node.is-current:focus>.el-tree-node__content) {
  background-color: #ecf5ff!important;
}
.node-item:hover {
  .node-button .node-button-item:hover {
    background: #eaeaea;
  }
}
.history-box {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  .header {
    display: flex;
    flex-direction: row;
    .history-left, .history-right {
      width: 50%;
      display: flex;
      flex-direction: column;
      .title {
        display: flex;
        align-items: center;
        flex-grow: 1;
        justify-content: center;
      }
    }
  }
  .body {
    height: 1px;
    flex-grow: 1;
    line-height: 25px;
    :deep(.CodeMirror-merge),
    :deep(.CodeMirror-merge-pane),
    :deep(.CodeMirror) {
      height: 100%;
    }
    :deep(.CodeMirror-merge-gap) {
      background: rgb(40,42,54);
      border-top: none;
      border-left: none;
      border-right: 1px solid rgb(147, 148, 154);
    }
    :deep(.CodeMirror-merge-r-chunk-start) {
      border-top: 1px solid rgb(62, 192, 125);
    }
    :deep(.CodeMirror-merge-r-chunk-end) {
      border-bottom: 1px solid rgb(62, 192, 125);
    }
    :deep(.CodeMirror-merge-r-chunk) {
      background: rgb(40,53,65);
    }
    :deep(.CodeMirror-merge-r-connect) {
      fill: rgb(40,53,65);
      stroke: rgb(62, 192, 125);
    }
  }
}
</style>